/**
 * Author : Jorge Mejuto Create : 06/05/2010
 */

package net.eyra.negocio.explotacion.informes.diario.pagina1;

import java.awt.BasicStroke;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TreeMap;

import net.eyra.negocio.entidades.explotacion.Lectura;
import net.eyra.utiles.PString;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.UnknownKeyException;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

public class GraficosProduccion {

    public JFreeChart GraficoProduccionAcumuladaMensual(TreeMap<String, Double> valores, String zona) {

        DefaultPieDataset dataset = new DefaultPieDataset();

        Iterator<String> iterator = valores.keySet().iterator();

        while (iterator.hasNext()) {
            String nombre = (String) iterator.next();
            dataset.setValue(PString.NombreCortoInstalacion(nombre), valores.get(nombre).doubleValue());
        }

        // JFreeChart chart = ChartFactory.createPieChart("Producción Acumulada Mensual Zona Noroeste", dataset, false, false, false);
        JFreeChart chart = ChartFactory.createRingChart("Producción Acumulada Mensual " + zona, dataset, false, false, false);
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setSectionOutlinesVisible(false);

        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} - {1} kW  ({2})", Locale.getDefault()));

        plot.setInteriorGap(0.001);
        plot.setMaximumLabelWidth(0.25);

        // iterator = dataset.getKeys().iterator();
        // while (iterator.hasNext())
        // plot.setExplodePercent((Comparable<String>) iterator.next(), 0.1);

        return chart;
    }

    public JFreeChart GraficoFactorCapacidadMensual(String zona) {

        DefaultPieDataset dataset = new DefaultPieDataset();

        dataset.setValue("P.E. SOMOZAS", (7686864.0 * 100) / (49600 * 24 * 26));
        dataset.setValue("P.E. NOVO", (3023473.0 * 100) / (18750 * 24 * 26));
        dataset.setValue("P.E. REQUEIXO", (2021001.0 * 100) / (10500 * 24 * 26));
        dataset.setValue("P.E. MONTE DAS AUGAS", (393866.0 * 100) / (3000 * 24 * 26));
        dataset.setValue("P.E. MONTE REDONDO", (6154842.0 * 100) / (49500 * 24 * 26));
        dataset.setValue("P.E. O BARRIGOSO", (524809.0 * 100) / (3000 * 24 * 26));
        dataset.setValue("P.E. OUTES", (5695788.0 * 100) / (33600 * 24 * 26));
        dataset.setValue("P.E. MONTE DA BARDA", (472644.0 * 100) / (3000 * 24 * 26));
        dataset.setValue("P.E. TOURIÑAN", (4887442.0 * 100) / (24650 * 24 * 26));

        JFreeChart chart = ChartFactory.createPieChart("Factor Capacidad Producción Acumulada " + zona, dataset, false, false, false);
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setSectionOutlinesVisible(false);

        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} - {1}%", new DecimalFormat("###.##"), new DecimalFormat("0.00%")));

        plot.setInteriorGap(0.001);
        plot.setMaximumLabelWidth(0.25);

        Iterator<String> iterator = dataset.getKeys().iterator();
        while (iterator.hasNext())
            plot.setExplodePercent((Comparable<String>) iterator.next(), 0.1);

        return chart;
    }

    public JFreeChart GraficoProduccionIncrementalAcumuladaMensual(TreeMap<String, List<Lectura>> valores, String zona) {

        TimeSeriesCollection dataset = new TimeSeriesCollection();

        Iterator<String> itr = valores.keySet().iterator();

        while (itr.hasNext()) {
            String nombre = (String) itr.next();
            TimeSeries x = new TimeSeries(PString.NombreCortoInstalacion(nombre));
            double suma = 0;
            for (Lectura lectura : valores.get(nombre)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(lectura.getPeriodo());
                suma += lectura.getActiva_exportada();
                x.add(new Day(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR)), suma);
            }
            dataset.addSeries(x);
        }

        JFreeChart chart = ChartFactory.createTimeSeriesChart("Producción Incremental Acumulada Mensual " + zona, "", "Producción (kW)", dataset,
                                                              true, false, false);

        XYPlot plot = (XYPlot) chart.getPlot();
        XYItemRenderer r = plot.getRenderer();

        int series = valores.size();
        for (int x = 0; x < series; x++)
            r.setSeriesStroke(x, new BasicStroke(4f));

        return chart;
    }

    public JFreeChart GraficoProduccionDiariaAcumuladaMensual(TreeMap<String, List<Lectura>> valores, String zona) {

        TimeSeriesCollection dataset = new TimeSeriesCollection();

        Iterator<String> itr = valores.keySet().iterator();

        while (itr.hasNext()) {
            String nombre = (String) itr.next();
            TimeSeries x = new TimeSeries(PString.NombreCortoInstalacion(nombre));
            for (Lectura lectura : valores.get(nombre)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(lectura.getPeriodo());
                x.add(new Day(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR)),
                      lectura.getActiva_exportada());
            }
            dataset.addSeries(x);
        }

        JFreeChart chart = ChartFactory.createTimeSeriesChart("Producción Diaria Acumulada Mensual " + zona, "", "Producción ()", dataset, true,
                                                              false, false);

        XYPlot plot = (XYPlot) chart.getPlot();
        XYItemRenderer r = plot.getRenderer();

        int series = valores.size();
        for (int x = 0; x < series; x++)
            r.setSeriesStroke(x, new BasicStroke(4f));

        return chart;
    }

    public JFreeChart GraficoProduccionDiariaAcumuladaMensual2(TreeMap<String, List<Lectura>> valores, String zona) {

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        Iterator<String> itr = valores.keySet().iterator();

        while (itr.hasNext()) {
            String nombre = (String) itr.next();
            for (Lectura lectura : valores.get(nombre)) {
                dataset.setValue(lectura.getActiva_exportada(), PString.NombreCortoInstalacion(nombre),
                                 lectura.getPeriodo().toString().substring(5, 10));
            }
        }

        // JFreeChart chart = ChartFactory.createAreaChart("Producción Diaria Acumulada Mensual "+zona, "", "Producción (kW)", dataset,
        // PlotOrientation.VERTICAL, true, false, false);

        JFreeChart chart = ChartFactory.createAreaChart("", "", "Producción (kW)", dataset, PlotOrientation.VERTICAL, true, false, false);

        CategoryPlot plot = chart.getCategoryPlot();
        plot.setForegroundAlpha(0.3f);

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
        domainAxis.setLowerMargin(0.0);
        domainAxis.setUpperMargin(0.0);

        return chart;
    }

    public JFreeChart GraficoProduccionDiariaPrecioMediol(TreeMap<String, List<Lectura>> valores, String zona, TreeMap<String, Double> precioMercado) {

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        Iterator<String> itr = valores.keySet().iterator();

        double suma = 0;
        while (itr.hasNext()) {
            String nombre = (String) itr.next();
            for (Lectura lectura : valores.get(nombre)) {
                String fecha = new SimpleDateFormat("dd").format(lectura.getPeriodo());
                try {
                    suma = lectura.getActiva_exportada() / 1000 + dataset.getValue("", fecha).doubleValue();
                } catch (UnknownKeyException e) {
                    suma = lectura.getActiva_exportada() / 1000;
                }
                dataset.addValue(suma, "", fecha);
            }
        }

        JFreeChart chart = ChartFactory.createBarChart("Producción Diaria y Precio Medio Diario " + zona, "", "Producción (MW)", dataset,
                                                       PlotOrientation.VERTICAL, false, false, false);

        CategoryPlot plot = chart.getCategoryPlot();

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLowerMargin(0.02);
        domainAxis.setUpperMargin(0.02);

        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
        renderer2.setSeriesStroke(0, new BasicStroke(4f));
        DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();

        BarRenderer r = (BarRenderer) plot.getRenderer();
        r.setMaximumBarWidth(0.03);

        itr = precioMercado.keySet().iterator();
        while (itr.hasNext()) {
            String fecha = (String) itr.next();
            if (fecha.length() > 0) dataset2.addValue(precioMercado.get(fecha), "", fecha.substring(0, 2));
        }

        NumberAxis axis2 = new NumberAxis("Precio Medio (€/MWh)");
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.setRenderer(1, renderer2);
        plot.mapDatasetToRangeAxis(1, 1);
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        return chart;

    }

    public JFreeChart GraficoFacturacionDiariaPrecioMediol(TreeMap<String, List<Lectura>> valores, String zona, TreeMap<String, Double> precioMercado) {

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        Iterator<String> itr = valores.keySet().iterator();

        double suma = 0;
        while (itr.hasNext()) {
            String nombre = (String) itr.next();
            for (Lectura lectura : valores.get(nombre)) {
                String fecha = new SimpleDateFormat("dd").format(lectura.getPeriodo());
                try {
                    suma = lectura.getActiva_exportada() + dataset.getValue("", fecha).doubleValue();
                } catch (UnknownKeyException e) {
                    suma = lectura.getActiva_exportada();
                }
                dataset.addValue(suma, "", fecha);
            }
        }

        JFreeChart chart = ChartFactory.createBarChart("Facturación Diaria y Precio Medio Diario " + zona, "", "Facturación (€)", dataset,
                                                       PlotOrientation.VERTICAL, false, false, false);

        CategoryPlot plot = chart.getCategoryPlot();

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLowerMargin(0.02);
        domainAxis.setUpperMargin(0.02);

        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());

        LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
        renderer2.setSeriesStroke(0, new BasicStroke(4f));
        DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();

        BarRenderer r = (BarRenderer) plot.getRenderer();
        r.setMaximumBarWidth(0.03);

        itr = precioMercado.keySet().iterator();
        while (itr.hasNext()) {
            String fecha = (String) itr.next();
            dataset2.addValue(precioMercado.get(fecha), "", fecha.substring(0, 2));
        }

        NumberAxis axis2 = new NumberAxis("Precio Medio (€/MWh)");
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.setRenderer(1, renderer2);
        plot.mapDatasetToRangeAxis(1, 1);
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        return chart;

    }
}
